function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;    
}

$(document).ready(function(){
    if (!getCookie('csrftoken')) {
        login_page = document.getElementById('login');
        if (login_page) {return}
        self.location='login.html'; 
    }
})

$(function(){
    $('#logout').on('click', function(){
        var api = '/webapp/logout';
        var csrftoken = getCookie('csrftoken');
        $.ajax({
            url: api,
            type: 'POST',
            dataType: 'json',
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function(data, status){
                if(data.status==200){
                    self.location='login.html';
                }         
            },
        });
    });

    $('#login').on('click', function(){
        username = $("#username").val();
        password = $("#password").val();
        data_err = document.getElementById('login-data-err');
        if (!username || !password) {
            data_err.style.display = '';
            return
        }
        data = {
            'uid': username,
            'password': password,
        }
        var api = '/backstage/login';
        var csrftoken = getCookie('csrftoken');
        $.ajax({
            url: api,
            type: 'POST',
            data: data,
            dataType: 'json',
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function(data, status){
                if(data.status==200){
                    $("#loginFailAlert").hide();
                    self.location='index.html'; 
                }
                else{
                    $("#loginFailAlert").show();
                }
            },
        });
    });
})
